package com.example.springboot2.service;

import com.example.springboot2.entity.Merchant;
import com.example.springboot2.entity.User;
import com.example.springboot2.exception.BusinessException;
import com.example.springboot2.repository.MerchantRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 商家服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MerchantService {

    private final MerchantRepository merchantRepository;
    private final UserService userService;

    /**
     * 根据ID查找商家
     */
    public Merchant findById(Long id) {
        return merchantRepository.findById(id)
                .orElseThrow(() -> new BusinessException("商家不存在"));
    }

    /**
     * 根据用户ID查找商家
     */
    public Optional<Merchant> findByUserId(Long userId) {
        return merchantRepository.findByUserId(userId);
    }

    /**
     * 获取商家信息
     */
    public Merchant getMerchantInfo(Long userId) {
        return findByUserId(userId)
                .orElseThrow(() -> new BusinessException("商家信息不存在"));
    }

    /**
     * 创建商家
     */
    @Transactional
    public Merchant createMerchant(Long userId, Merchant merchant) {
        User user = userService.findById(userId);
        
        // 检查用户是否已有商家信息
        if (findByUserId(userId).isPresent()) {
            throw new BusinessException("商家信息已存在");
        }
        
        // 检查店铺名称是否已存在
        if (merchantRepository.existsByShopName(merchant.getShopName())) {
            throw new BusinessException("店铺名称已存在");
        }
        
        merchant.setUser(user);
        return merchantRepository.save(merchant);
    }

    /**
     * 更新商家信息
     */
    @Transactional
    public Merchant updateMerchantInfo(Long userId, Merchant merchantInfo) {
        Merchant existingMerchant = getMerchantInfo(userId);
        
        // 检查店铺名称是否已被其他商家使用
        if (!merchantInfo.getShopName().equals(existingMerchant.getShopName()) &&
            merchantRepository.existsByShopName(merchantInfo.getShopName())) {
            throw new BusinessException("店铺名称已被其他商家使用");
        }
        
        // 更新基本信息
        existingMerchant.setShopName(merchantInfo.getShopName());
        existingMerchant.setDescription(merchantInfo.getDescription());
        existingMerchant.setLogo(merchantInfo.getLogo());
        existingMerchant.setAddress(merchantInfo.getAddress());
        existingMerchant.setProvince(merchantInfo.getProvince());
        existingMerchant.setCity(merchantInfo.getCity());
        existingMerchant.setDistrict(merchantInfo.getDistrict());
        existingMerchant.setLatitude(merchantInfo.getLatitude());
        existingMerchant.setLongitude(merchantInfo.getLongitude());
        existingMerchant.setBusinessHours(merchantInfo.getBusinessHours());
        existingMerchant.setContactPhone(merchantInfo.getContactPhone());
        
        return merchantRepository.save(existingMerchant);
    }

    /**
     * 提交商家认证
     */
    @Transactional
    public void submitCertification(Long userId, String businessLicense, String idCardFront, String idCardBack) {
        Merchant merchant = getMerchantInfo(userId);
        
        merchant.setBusinessLicense(businessLicense);
        merchant.setIdCardFront(idCardFront);
        merchant.setIdCardBack(idCardBack);
        merchant.setCertificationStatus(Merchant.CertificationStatus.PENDING);
        
        merchantRepository.save(merchant);
        log.info("商家提交认证: {}", merchant.getShopName());
    }

    /**
     * 审核商家认证
     */
    @Transactional
    public void approveCertification(Long merchantId, boolean approved, String remark) {
        Merchant merchant = findById(merchantId);
        
        if (approved) {
            merchant.setCertificationStatus(Merchant.CertificationStatus.APPROVED);
        } else {
            merchant.setCertificationStatus(Merchant.CertificationStatus.REJECTED);
        }
        merchant.setCertificationRemark(remark);
        
        merchantRepository.save(merchant);
        log.info("商家认证审核: {} - {}", merchant.getShopName(), approved ? "通过" : "拒绝");
    }

    /**
     * 更新商家状态
     */
    @Transactional
    public void updateMerchantStatus(Long merchantId, Merchant.MerchantStatus status) {
        Merchant merchant = findById(merchantId);
        merchant.setStatus(status);
        merchantRepository.save(merchant);
        log.info("更新商家状态: {} - {}", merchant.getShopName(), status);
    }

    /**
     * 检查店铺名称是否存在
     */
    public boolean existsByShopName(String shopName) {
        return merchantRepository.existsByShopName(shopName);
    }
}
